<template>
	<view>

	</view>
</template>

<script>
	import { mapState, mapActions } from 'vuex'
	import QQMapWX from "@/libs/qqmap-wx-jssdk.min.js";
	import { isEmpty } from '@/utils/index.js';
	
	let qqmapsdk;
	const mapInit = () => {
		qqmapsdk = new QQMapWX({
			key: "DGHBZ-5UUL3-C4I3F-OTYMB-43ODE-KWFAW"
		})
	}
	
	export default {
		name: "com-map",
		props:{
			address:''
		},
		data() {
			return {
				
			};
		},
		computed: {
			//引入store全局变量
			...mapState(['mylocation','mylocationState'])
		},
		mounted() {
			mapInit();
		},
		methods: {
			//引入store全局方法
			...mapActions(['getlocationAction']),
			//获取当前定位
			getLocation() {
				const that = this;
				uni.getLocation({
					type: 'gcj02',
					geocode: true,
					success: res => {
						const { latitude, longitude, address } = res;
						const myloc = {'latitude': latitude, 'longitude': longitude, city: address?.city || ''};
						
						if (isEmpty(myloc.city)) {
							qqmapsdk.reverseGeocoder({
								location: { latitude, longitude },
								success: res1 => {
									const { city } = res1.result.address_component;
									if (!isEmpty(city)) {
										myloc.city = city;
										that.getlocationAction(myloc)
										that.$emit('myevent', myloc) 
									}
								}
							})
						} else {
							that.getlocationAction(myloc)
							that.$emit('myevent', myloc) 
						}
					},
					fail: err => {
						console.log('获取定位失败:', JSON.stringify(err))
					}
				})
			},
			//判断是否开启定位授权，如果未开启则引导开启手机定位权限
			setlocation() {
				const that = this;
				
				// Get the current platform
				const systemInfo = uni.getSystemInfoSync();
				const platform = systemInfo.platform;
				
				if (systemInfo.mp && systemInfo.mp.platform === 'mp-weixin') {
					uni.authorize({
						scope: 'scope.userLocation',
						success() {
							that.getLocation();
						},
						fail() {
							uni.showModal({
								title:'是否授权当前位置',
								content: '需要获取您的地理位置，请确认授权，否则部分功能将无法使用',
								confirmText: "确认",
								cancelText: '取消',
								success: (res) => {
									if (res.confirm) {
										uni.openSetting({
											success: (res) => {
												that.getLocation();
											}
										})
									} else {
										uni.$u.toast('您已取消授权')
										return false;
									}
								}
							})
							return false;
						}
					});
				} 
				else {
					that.getLocation();
				}
			},
			//导航到第三方APP
			toMapAPP(){
				if (!this.mylocationState) {
					this.setlocation()
					return
				}
				uni.openLocation({
					latitude: this.mylocation.latitude,
					longitude: this.mylocation.longitude,
					address:this.address,
					success: function () {
						console.log('success');
					}
				});
			}
		}
	}
</script>